package util;

import com.aspose.words.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

/**
 * @author changwei
 * @date 2022/5/19
 */
@Slf4j
public class SignContractUtil {

    public static void fillApplicationForm(Document document, Map<String, Object> dataMap) {
        replaceText(document, dataMap);
    }

    /**
     * 文字替换
     */
    public static void replaceText(Document document, Map<String, Object> dataMap) {
        FindReplaceOptions options = new FindReplaceOptions();
        if (dataMap != null) {
            dataMap.forEach((key, value) -> {
                try {
                    document.getRange().replace(key, value == null ? StringUtils.SPACE : (String) value, options);
                } catch (Exception e) {
                    log.error("Replace tempale value fail with key {} value {}: {}", key, value, e);
                }
            });
        }
    }

    /**
     * 填充字段
     *
     * @param document
     * @param data
     * @return
     */
    public static Document fillData(Document document, Map<String, Object> data) throws Exception {
            MailMerge mailMerge = document.getMailMerge();
            //获取该文档的所有文本域
            String[] fieldNames = mailMerge.getFieldNames();
            DocumentBuilder builder = new DocumentBuilder(document);
            for (String field : fieldNames) {
                if(data.get(field) instanceof File){
                    File file = (File) data.get(field);
                    builder.moveToMergeField(field);
                    try(InputStream singImageIs = new FileInputStream(file)){
                        builder.insertImage(singImageIs);
                    }
                }
                if (data.get(field) instanceof String) {
                    builder.moveToMergeField(field);
//                    Font font = builder.getFont();
//                    int underline = font.getUnderline();
//                    font.clearFormatting();
//                    font.setUnderline(underline);
                    builder.write((String) data.get(field));
                }
            }
            return document;
    }


    /**
     * 删除多余文本域
     */
    public static void deleteField(Document document) throws Exception {
        MailMerge mailMerge = document.getMailMerge();
        mailMerge.deleteFields();
    }

    public static void saveDocument(Document document, File file, Integer saveFormat) throws Exception {
        SaveOptions options = SaveOptions.createSaveOptions(saveFormat);
        options.setMemoryOptimization(true);
        document.save(file.getAbsolutePath(), options);
    }
}
